<template>
  <el-dialog v-model="show" :title="title" width="50%" align-center @close="handleClose">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="配件类型" prop="componentType">
            <el-select v-model="ruleForm.componentType" placeholder="请选择配件类型" style="width: 200px;">
              <el-option v-for="item in props.initList?.component_type" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件名称" prop="componentName">
            <el-input v-model="ruleForm.componentName" placeholder="请输入配件名称" style="width: 200px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="配件模型" prop="fileList">
            <el-upload ref="upload" v-model:file-list="ruleForm.fileList" style="display: flex; align-items: center;"
              :action="uploadImgUrl" :headers="headers" :limit="1" :on-success="handleUploadSuccess"
              :on-exceed="handleExceed">
              <template #trigger>
                <el-button type="primary">上传模型</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配件数量" required>
            <el-row>
              <el-col :span="11">
                <el-form-item prop="low">
                  <el-input v-model.number="ruleForm.low" type="number" :min="1"
                    @input="(val: any) => ruleForm.low = Math.floor(Math.max(1, Number(val)))"
                    placeholder="请输入最小配件数量" />
                </el-form-item>
              </el-col>
              <el-col class="text-center" :span="2">
                <span class="text-gray-500">-</span>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="high">
                  <el-input v-model.number="ruleForm.high" type="number" :min="ruleForm.low"
                    @input="(val: any) => ruleForm.high = Math.floor(Math.max(ruleForm.low, Number(val)))"
                    placeholder="请输入最大配件数量" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配件展示图" prop="imageUrl">
            <el-upload ref="designSketchRef" :show-file-list="false" drag :action="uploadImgUrl" :headers="headers"
              multiple :auto-upload="true" :on-success="handleDesignSketchSuccess"
              :before-upload="beforedeSignSketchUpload">
              <img style="height: 100px;" v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" />
              <template v-else>
                <div style="padding-top: 10px;">
                  <uploadStyle type="1" icon="PictureFilled" />
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="mb-4">
        <el-button v-for="(item, index) in props.initList?.attribute_type" :key="index"
          @click="openModal(index, { volume_interval: props.initList?.volume_interval, attributeType: item.value })"
          :type="getButtonType(index)">添加{{
            item.label }}</el-button>
      </div>
    </el-form>
    <!-- 展示区 -->
    <div class="exhibition">
      <!-- 颜色 图片 -->
      <div class="colourContainer" v-if="colourList.length != 0">
        <el-descriptions title="颜色"></el-descriptions>
        <div class="colourContainer_list">
          <div class="colourContainer_item" style="position: relative;" @click="openModal(0, {
            list: {
              index,
              item: JSON.parse(JSON.stringify(item))
            }, volume_interval: props.initList?.volume_interval
          })" v-for="(item, index) in colourList" :key="index">
            <el-image style="width: 100px; height: 100px" :src="item.imageUrl" />
            <div class="colourContainer_item_name">{{ item.attributeName }}</div>
            <img @click.stop="deleteColor(index)" src="@/assets/images/delete.png"
              style="position: absolute; top: 4px; right:4px; width: 20px; height: 20px;" alt="">
          </div>
        </div>
      </div>

      <div class="exhibition_container">
        <div v-if="materialList.length != 0">
          <el-descriptions title="材质" :column="1">
            <el-descriptions-item v-for="(item, index) in materialList" :key="index">
              <template #label>
                <span style="cursor: pointer;color:#409EFF;text-decoration: underline;" @click="openModal(1, {
                  joinList: {
                    index,
                    item: JSON.parse(JSON.stringify(item))
                  }, volume_interval: props.initList?.volume_interval,
                })">{{ item.attributeName }}</span>
              </template>
              <el-tag type="danger" style="cursor: pointer;" @click="deleteClick('material', index)">删除</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-if="grammageList.length != 0">
          <el-descriptions title="克重" :column="1">
            <el-descriptions-item v-for="(item, index) in grammageList" :key="index">
              <template #label>
                <span style="cursor: pointer;color:#409EFF;text-decoration: underline;" @click="openModal(2, {
                  list: {
                    index,
                    item: JSON.parse(JSON.stringify(item))
                  }, volume_interval: props.initList?.volume_interval
                })">{{ item.attributeName }}g</span>
              </template>
              <el-tag type="danger" style="cursor: pointer;" @click="deleteClick('grammage', index)">删除</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-if="packagingMethodList.length != 0">
          <el-descriptions title="包装方式" :column="1">
            <el-descriptions-item v-for="(item, index) in packagingMethodList" :key="index">
              <template #label><span style="cursor: pointer;color:#409EFF;text-decoration: underline;" @click="openModal(3, {
                list: {
                  index,
                  item: JSON.parse(JSON.stringify(item))
                }, volume_interval: props.initList?.volume_interval
              })">{{ item.attributeName }}</span></template>
              <el-tag type="danger" style="cursor: pointer;" @click="deleteClick('packagingMethod', index)">删除</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" v-loading="loading" @click="handleSubmit(ruleFormRef)">{{ btnTitle }}</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 材质 -->
  <Material :visible="modals[1].visible" :initList="modals[1].data" @submit="getMaterial"
    @modify="(data: any) => modifyClick(data, 'material')" @close="closeModal(1)" />
  <!-- 克重 -->
  <Grammage :visible="modals[2].visible" :initList="modals[2].data" @submit="getGrammage"
    @modify="(data: any) => modifyClick(data, 'grammage')" @close="closeModal(2)" />
  <!-- 包方式 -->
  <PackagingMethod :visible="modals[3].visible" :initList="modals[3].data" @submit="getPackagingMethod"
    @modify="(data: any) => modifyClick(data, 'packagingMethod')" @close="closeModal(3)" />
  <!-- 颜色 -->
  <colorModel :visible="modals[0].visible" :initList="modals[0].data"
    @modify="(data: any) => modifyClick(data, 'colour')" @submit="getColour" @close="closeModal(0)" />
</template>

<script setup lang="ts">
import { globalHeaders } from "@/utils/request";
import uploadStyle from '@/components/uploadStyle.vue'

import Material from './material.vue'
import Grammage from './grammage.vue'
import PackagingMethod from './packagingMethod.vue'
import colorModel from './colour.vue'

import { genFileId, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { useModal } from '@/hooks/useModal'

import { addDemo, updateDemo } from '@/api/accessoryManagement/index'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);
const { modals, openModal, closeModal } = useModal(4)

const show = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const loading = ref(false);
const btnTitle = ref('新 增');
const title = ref('新增配件')

watch(() => props.visible, async (newValue) => {
  show.value = newValue
  if (newValue) {
    if (props.initList?.detailsObj && Object.keys(props.initList?.detailsObj).length != 0) {
      ruleForm.value.componentType = props.initList?.detailsObj?.componentType
      ruleForm.value.componentName = props.initList?.detailsObj?.componentName
      ruleForm.value.low = props.initList?.detailsObj?.low
      ruleForm.value.high = props.initList?.detailsObj?.high
      ruleForm.value.imageUrl = props.initList?.detailsObj?.imageUrl
      ruleForm.value.fileList = [{
        name: '建模1',
        url: props.initList?.detailsObj?.modelUrl
      }]
      btnTitle.value = '修 改'
      title.value = '修改配件'

      if (props.initList?.detailsObj?.attributeVos.length != 0 && props.initList?.volume_interval.length != 0) {
        props.initList?.detailsObj?.attributeVos.map((item: any) => {
          if (item.joinList.length != 0) {
            // item.joinList = item.joinList.map((element: any) => {
            //   return {
            //     type: element.type,
            //     price: element.price,
            //     label: props.initList?.volume_interval.filter((labItem: any) => labItem.value == element.type)[0]?.label
            //   }
            // })

            // item.joinList = props.initList?.volume_interval.map((element: any) => {
            //   let price = 0
            //   if(element.value > 5) {
            //     price = item.joinList.filter((labItem: any) => labItem.type == 5)[0]?.price || 0
            //   }else {
            //     price = item.joinList.filter((labItem: any) => labItem.type == element.value)[0]?.price || 0
            //   }

            //   return {
            //     type: element.value,
            //     price,
            //     label: element.label
            //   }
             
            // })

            item.joinList = props.initList?.volume_interval.map((element: any) => {
              return {
                type: element.value,
                price: item.joinList.filter((labItem: any) => labItem.type == element.value)[0]?.price || 0,
                label: element.label
              }
            })
          }
        })
      }


      if (props.initList?.attribute_type.length != 0 && props.initList?.detailsObj?.attributeVos.length != 0) {
        props.initList?.attribute_type.forEach((element: any) => {
          props.initList?.detailsObj?.attributeVos.forEach((item: any) => {
            if (element.value == item.attributeType) {
              if (element.value == 2) {
                materialList.value.push(item)
              } else if (element.value == 3) {
                grammageList.value.push(item)
              } else if (element.value == 4) {
                packagingMethodList.value.push(item)
              } else if (element.value == 1) {
                colourList.value.push(item)
              }
            }
          });
        });
      }
    } else {
      btnTitle.value = '新 增'
      title.value = '新增配件'
    }
  }
}, { deep: true });

const materialList = ref<any>([]) // 材质列表
const grammageList = ref<any>([]) // 克重列表
const packagingMethodList = ref<any>([]) // 包装方式列表
const colourList = ref<any>([]) // 颜色列表

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<any>({
  componentType: '',
  componentName: '',
  fileList: [],
  low: null,
  high: null,
  imageUrl: ''
})
const fileTypes = ['image/png', 'image/jpeg']

const rules = reactive<any>({
  componentType: [
    { required: true, message: '请选择配件类型', trigger: ['change', 'blur'] },
  ],
  componentName: [
    { required: true, message: '请输入配件名称', trigger: 'blur' },
  ],
  // fileList: [
  //   { required: true, message: '请上传模型', trigger: ['change', 'blur'] },
  // ],
  low: [
    { required: true, message: '请输入最小配件数量', trigger: 'blur' },
  ],
  high: [
    { required: true, message: '请输入最大配件数量', trigger: 'blur' },
  ],
  imageUrl: [
    { required: true, message: '请上传配件展示图', trigger: ['change', 'blur'] },
  ],
})

const upload = ref<UploadInstance>()

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (colourList.value.length == 0) return proxy?.$modal.msgError('请添加颜色')
      loading.value = true
      let list = [...colourList.value, ...materialList.value, ...grammageList.value, ...packagingMethodList.value]
      let query = {
        modelUrl: ruleForm.value.fileList.length != 0 ? ruleForm.value.fileList[0].url : '',
        attributeBos: list,
        ...ruleForm.value
      }

      if (props.initList?.id) {
        try {
          query.id = props.initList?.id
          const { code } = await updateDemo(query)
          if (code == 200) {
            proxy?.$modal.msgSuccess('修改成功');
            loading.value = false
            emits('submit', true);
            handleClose();
          }
        } catch (error) {
          loading.value = false
          console.log(error)
        }
      } else {
        try {
          const { code } = await addDemo(query)
          if (code == 200) {
            proxy?.$modal.msgSuccess('新增成功');
            loading.value = false
            emits('submit', true);
            handleClose();
          }
        } catch (error) {
          loading.value = false
          console.log(error)
        }
      }




    } else {
      console.log('error submit!', fields)
    }
  })
}

/**
 * 删除颜色
 */
const deleteColor = (index: number) => {
  colourList.value.splice(index, 1)
}

/**
 * 上传模型 就上传一个 后续上传直接替换掉
 */
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
/**
 * 上传模型成功
 */
const handleUploadSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.value.fileList = [{
    name: response.data.fileName,
    url: response.data.url
  }]
};

/**
 * 上传配件展示图格式的判定
 */
const beforedeSignSketchUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error('请上传jpg/png格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片不可超过 5MB!')
    return false
  }
  return true
};

/**
 * 上传配件展示图 成功回调
 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.value.imageUrl = response.data.url
};

/**
 * 添加材质的回调
 */
const getMaterial = (data: any) => {
  materialList.value = [...materialList.value, {
    attributeName: data.attributeName,
    attributeType: data.attributeType,
    joinList: data.joinList
  }]
}

/**
 * 添加克重
 */
const getGrammage = (data: any) => {
  grammageList.value = [...grammageList.value, {
    attributeName: data.attributeName,
    attributeType: data.attributeType,
    joinList: data.joinList
  }]
}

/**
 * 添加包装方式
 */
const getPackagingMethod = (data: any) => {
  packagingMethodList.value = [...packagingMethodList.value, {
    attributeName: data.attributeName,
    attributeType: data.attributeType,
    joinList: data.joinList
  }]
}

/**
 * 添加颜色
 */
const getColour = (data: any) => {
  colourList.value = [...colourList.value, {
    attributeName: data.attributeName,
    attributeType: data.attributeType,
    color: data.color,
    imageUrl: data.imageUrl,
    joinList: data.joinList
  }]
}

/**
 * 修改
 */
const modifyClick = (data: any, name: string) => {
  if (name == 'material') {
    materialList.value[data.index] = data.data
  } else if (name == 'grammage') {
    grammageList.value[data.index] = data.data
  } else if (name == 'packagingMethod') {
    packagingMethodList.value[data.index] = data.data
  } else if (name == 'colour') {
    colourList.value[data.index] = data.data
  }
}

/**
 * 删除
 */
const deleteClick = (name: string, index: number) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      if (name == 'material') {
        materialList.value.splice(index, 1)
      } else if (name == 'grammage') {
        grammageList.value.splice(index, 1)
      } else if (name == 'packagingMethod') {
        packagingMethodList.value.splice(index, 1)
      } else if (name == 'colour') {
        colourList.value.splice(index, 1)
      }
    })
}

const getButtonType = (index: number) => {
  let str = ''
  switch (index) {
    case 0:
      str = ''
      break;
    case 1:
      str = 'primary'
      break;
    case 2:
      str = 'success'
      break;
    case 3:
      str = 'warning'
      break;
  }
  return str
}

const handleClose = () => {
  ruleFormRef.value?.resetFields();
  materialList.value.length = 0
  grammageList.value.length = 0
  packagingMethodList.value.length = 0
  colourList.value.length = 0
  emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
.exhibition {
  width: 100%;
  max-height: 400px;
  overflow-y: auto;
  padding: 5px;

  .colourContainer {
    cursor: pointer;

    &_list {
      display: flex;
      align-items: center;
      height: 100%;
      overflow-x: auto;
      margin-top: 6px;
    }

    &_item {
      margin-right: 10px;
      width: 100px;

      .el-image {
        border-radius: 8px;
      }

      &_name {
        text-align: center;
        width: 100%;
      }
    }

  }

  &_container {
    margin-top: 10px;
    display: flex;

    >div {
      flex: 1;
    }
  }
}



::v-deep .el-upload-list {
  margin: 0;
  width: 100px;
}

::v-deep .el-upload-list__item {
  margin-bottom: 0;
}

::v-deep .el-upload-dragger {
  padding: 0px 4px !important;
  height: 100px !important;
  width: 260px;
}

::v-deep .el-divider--horizontal {
  margin: 12px 0;
}
</style>
